/*
 * set mailings tree
 */
var refreshWidgetSettings = {
	storeUrl: 'index.php/mailings/getMailings',
	treeCls: '.treeMailings',
	idPrefix: 'treeMailings',
	controllerName: 'mailings'
}
Qlsolution.widgets.tree.start({
    storeUrl: 'index.php/mailings/getMailings',
	treeCls: '.treeMailings',
	idPrefix: 'treeMailings',
	controllerName: 'mailings'
});

/*
 * set mailings mailing portlet
 */
Qlsolution.widgets.portlet.start({
	selector: '.widgetPortlet .column',
	placeholder: 'widgetPortletPlaceholder br7',
	columnWidth: '100%',
	connectWith: '.column',
	selectorElement: '.portlet'
});

function disableAllPanels(){
	Qlsolution.tools.disable({
		selector: [
			$('#mailingDetails .elementContent'), 
			$('#mailingContent .elementContent'), 
			$('#mailingTestMailing .elementContent'),
			$('#mailingRecipients .elementContent:first'),
			$('#mailingAddRecipients .elementContent'),
			$('#mailingActions .elementContent')
		]
	});
}
disableAllPanels();

/*
 * set controller
 */
Qlsolution.controllers.mailings = {
	idElement: '',
	store: {
		saveDetails: 'index.php/mailings/updateDetails',
		saveContent: 'index.php/mailings/updateContent',
		testMailing: 'index.php/mailings/testMailing',
		saveRecipients: 'index.php/mailings/saveRecipients',
		sendMailing: 'index.php/mailings/sendMailing',
		removeMailing: 'index.php/mailings/removeMailing'
	},
	limitPerPage: 50,

	handleTreeLeaf: function(idElement){
		//set element id
		Qlsolution.controllers.mailings.idElement = idElement;

		//get mailings details
		var paramsData = new Object();
		paramsData['id_node'] = Qlsolution.controllers.mailings.idElement;
		$.ajax({
			type: 'post',
			data: 'params=' + $.toJSON(paramsData),
			url: Qlsolution.baseUrl + 'index.php/mailings/getDetails',
			success: function(msg){
				var details = $.parseJSON(msg);
				Qlsolution.controllers.mailings.updateDetails(details);
				Qlsolution.controllers.mailings.updateContent(details);
				Qlsolution.controllers.mailings.updateRecipients(details);
				Qlsolution.controllers.mailings.testMailing(details);
				Qlsolution.controllers.mailings.addRecipients(details);
				Qlsolution.controllers.mailings.actions(details);
				Qlsolution.controllers.mailings.remove(details);
				Qlsolution.tools.disableRemove({
					selector: [
						$('#mailingDetails .elementContent'), 
						$('#mailingContent .elementContent'), 
						$('#mailingTestMailing .elementContent'),
						$('#mailingRecipients .elementContent:first'),
						$('#mailingAddRecipients .elementContent'),
						$('#mailingActions .elementContent')
					]
				})
			}
		});
	},

	updateDetails: function(details){
		var $selector = $('#mailingDetails');
		for(val in details[0]){
			$selector.find('input[name="' + val + '"]').val(details[0][val]);
		}

		//details submit
		$selector.find('form').unbind('submit');
		$selector.find('form').submit(function(){
			var paramsData = new Object();
			$selector.find('form input').each(function(key, val){
				paramsData[$(this).attr('name')] = $(this).val();
			});
			$.ajax({
				type: 'post',
				url: Qlsolution.controllers.mailings.store.saveDetails,
				data: 'params=' + $.toJSON(paramsData),
				success: function(msg){
					Qlsolution.alerts.parseMsg({
						msg: msg,
						success: 'Data were saved',
						warning: 'Error.',
						selector: $selector.find('.elementContent')
					});
				}
			});
			return false;
		});
	},

	updateContent: function(details){
		var $selector = $('#mailingContent');
		$selector.find('#email_content').html(details[0]['email_content']);

		//content edit
		var editor,
			html = details[0]['email_content'];
		
		$selector.find('#email_editor').html('');
		$selector.find('.btn').unbind('click');
		$selector.find('.btn').click(function(){
			if(editor){
				html = editor.getData();
				$selector.find('#email_content').html(editor.getData());
				editor.destroy();
				editor = null;

				//save
				var paramsData = new Object();
				paramsData['id_node'] = details[0]['id_node'];
				paramsData['email_content'] = $selector.find('#email_content').html();
				$.ajax({
					type: 'post',
					url: Qlsolution.controllers.mailings.store.saveContent,
					data: 'params=' + $.toJSON(paramsData),
					success: function(msg){
						Qlsolution.alerts.parseMsg({
							msg: msg,
							success: 'Data were saved',
							warning: 'Error.',
							selector: $selector.find('.elementContent')
						});
					}
				});
			}
			else{
				var config = {
					language: 'en'
				};
				$selector.find('#email_content').html('');
				editor = CKEDITOR.appendTo('email_editor', config, html);
			}
		});
	},
	
	/*
	 * update recipients
	 */
	updateRecipients: function(details){
		Qlsolution.widgets.grid.start({
			cls: '.widgetGrid',
			storeUrl: 'index.php/mailings/getRecipients',
			idNode: details[0]['id_node'],
			page: 1
		});
	},

	testMailing: function(details){
		var $selector = $('#mailingTestMailing');
		$selector.find('form').unbind('submit');
		$selector.find('form').submit(function(){
			var paramsData = new Object();
			paramsData['id_node'] = details[0]['id_node'];
			paramsData['test_recipients'] = $selector.find('form textarea').val();
			$.ajax({
				type: 'post',
				url: Qlsolution.controllers.mailings.store.testMailing,
				data: 'params=' + $.toJSON(paramsData),
				success: function(msg){
					if(Qlsolution.alerts.parseMsg({
						msg: msg,
						success: 'Test was sent',
						warning: 'Error.',
						selector: $selector.find('.elementContent')
					})){
						$selector.find('form textarea').val('');
					}
				}
			});
			return false;
		});
	},

	addRecipients: function(details){
		var $selector = $('#mailingAddRecipients');
		$selector.find('form').unbind('submit');
		$selector.find('form').submit(function(){
			var paramsData = new Object();
			paramsData['id_node'] = details[0]['id_node'];
			paramsData['recipients'] =  $selector.find('form textarea').val();
			$.ajax({
				type: 'post',
				url: Qlsolution.controllers.mailings.store.saveRecipients,
				data: 'params=' + $.toJSON(paramsData),
				success: function(msg){
					if(Qlsolution.alerts.parseMsg({
						msg: msg,
						success: 'Data were saved',
						warning: 'Error.',
						selector: $selector.find('.elementContent')
					})){
						Qlsolution.controllers.mailings.updateRecipients(details);
					}
				}
			});
			return false;
		});
	},
	
	actions: function(details){
		var $selector = $('#mailingActions'),
			firstClick = true;
		$selector.find('.btn.sendMailing').unbind('click')
		$selector.find('.btn.sendMailing').click(function(){
			//show progress bar
			if(firstClick){
				Qlsolution.tools.progressBar({
					selector: $selector.find('.elementContent')
				});
				firstClick = false;
			}
			//disable panels
			Qlsolution.tools.disable({
				selector: [
					$('#mailingDetails .elementContent'), 
					$('#mailingContent .elementContent'), 
					$('#mailingTestMailing .elementContent'),
					$('#mailingAddRecipients .elementContent')
				]
			});
			//new object
			var paramsData = new Object(),
				$self = $(this);
			paramsData['id_node'] = details[0]['id_node'];
			$.ajax({
				type: 'post',
				url: Qlsolution.controllers.mailings.store.sendMailing,
				data: 'params=' + $.toJSON(paramsData),
				dataType: 'json',
				success: function(msg){
					if(parseInt(msg.code,10) == 200){
						if(msg.countSent != msg.countAll){
							//refresh progress bar
							Qlsolution.tools.progressBar({
								total: msg.countAll,
								count: msg.countSent,
								selector: $selector.find('.elementContent')
							})
							//send next
							$self.click();
						}
						else{
							//remove disable panels
							Qlsolution.tools.disableRemove({
								selector: [
									$('#mailingDetails .elementContent'), 
									$('#mailingContent .elementContent'), 
									$('#mailingTestMailing .elementContent'),
									$('#mailingAddRecipients .elementContent')
								]
							});
							//remove progress bar
							Qlsolution.tools.progressBarRemove({
								selector: $selector.find('.elementContent')
							});
							//show alert
							Qlsolution.alerts.showAlert({
								selector: $selector.find('.elementContent'),
								type: 'success',
								content: 'Mail was sent to all recipients'
							});
						}
						//update grid
						Qlsolution.controllers.mailings.updateRecipients(details);
					}
				}
			});
			return false;
		});
	},
	
	remove: function(details){
		var $selector = $('.widgetTree.treeMailings');
		$selector.find('.elementMenu .btnIco.delete').unbind('click');
		$selector.find('.elementMenu .btnIco.delete').click(function(){
			var paramsData = new Object();
			paramsData['id_node'] = details[0]['id_node'];
			$.ajax({
				type: 'post',
				url: Qlsolution.controllers.mailings.store.removeMailing,
				data: 'params=' + $.toJSON(paramsData),
				success: function(msg){
					Qlsolution.widgets.tree.load(refreshWidgetSettings);
					disableAllPanels();
				}
			});
		})
	}
};

/*
 * my handlers
 */
var $selector = $('.widgetTree.treeMailings');
$selector.find('.elementMenu .folderAdd').click(function(){
	/*
	 * dialog box - add folder
	 */
	Qlsolution.widgets.dialog.start({
		idElement: '#folderAddForm',
		title: 'Create new folder',
		storeUrl: 'index.php/mailings/saveMailings',
		refreshWidgetSettings: {
			storeUrl: 'index.php/mailings/getMailings',
			treeCls: '.treeMailings',
			idPrefix: 'treeMailings'
		},
		refreshWidgetType: 'tree',
		type: 'form',
		autoOpen: false,
		height: 150,
		width: 300,
		inputFields: [{
			type: 'text',
			label: 'Name',
			name: 'name',
			validate: 'required'
		},{
			type: 'hidden',
			name: 'is_mailing',
			value: '0'
		}]
	});

});

$selector.find('.elementMenu .emailAdd').click(function(){
	/*
	 * dialog box - add mailing
	 */
	Qlsolution.widgets.dialog.start({
		idElement: '#folderAddMailing',
		title: 'Create new mailing',
		storeUrl: 'index.php/mailings/saveMailings',
		refreshWidgetSettings: {
			storeUrl: 'index.php/mailings/getMailings',
			treeCls: '.treeMailings',
			idPrefix: 'treeMailings',
			controllerName: 'mailings'
		},
		refreshWidgetType: 'tree',
		type: 'form',
		autoOpen: false,
		height: 150,
		width: 300,
		inputFields: [{
			type: 'text',
			label: 'Name',
			name: 'name',
			validate: 'required'
		},{
			type: 'hidden',
			name: 'is_mailing',
			value: '1'
		}]
	});
});